var protocol=require("../../netbus/protocol");
var netbus=require("../../netbus/netbus");
var Cmd=require("../Cmd");

var server={
	name:"gateway",
	is_transfer:true,

	//登录成功前
	is_before_login:function(stype,ctype){
		
		//客户端发来:
		//GUEST_LOGIN,还没登录,此时session_id是socket_id,
		//USER_LOGIN,还没登录,此时session_id是socket_id,
		//PHONE_REG_VALIDATE,手机还没注册,没有用户,此用session_id是socket_id,
		//PHONE_REG,手机还没注册,没有用户,此时session_id是socket_id,
		//
		
		if (stype==Cmd.Stype.GameSys && ctype==Cmd.Request.GameSys.USER_LOGIN){
			return true;
		}

		return false;
	},


	//接收客户端发来的数据
	on_recv_client_cmd:function(session,stype,ctype,utag,proto_type,body){
		//将client发来的数据转发给app_server
		var app_server_session=netbus.get_app_server_session(stype);
		if (!app_server_session){
			return;
		}

		//登录成功前,session_id是socket_id
		//登录成功后,session_id是用户在数据库中的id
		if (this.is_before_login(stype,ctype)){
			//非法
			if (session.session_id<100000){
				return;
			}
		}
		
		//1、登录前还没有得到数据库中的用户id,所以使用临时socket id
		//2、登录后已经将session_id改成了用户id
		//client的socket id
		utag=session.session_id;
		
		//打入用户标识
		body.writeUInt32BE(utag,4);
		//直接发送到app_server
		app_server_session.send_cmd(body);
	},

	//接收到app_server发来的数据
	on_recv_app_server_cmd:function(session,stype,ctype,utag,proto_type,body){

		//将app_server发来的数据转发给client
		var client_session=netbus.get_client_session(utag);
		if (!client_session){
			return;
		}


		//1、用户验证通过，utag是socket id ,要将session_id改成用户id body.id
		//2、用户验证不通过，utag是socket id,不做任何处理
		if (stype==Cmd.Stype.GameSys && ctype==Cmd.Request.GameSys.USER_LOGIN){
			//将数据解码
			var obj=protocol.decode(proto_type, body);
			if (obj.Respones==Cmd.Respones.OK){

				//已经在一台设备上登录了
				var prev_client_session=netbus.get_client_session(obj.id);
				if (prev_client_session){
					prev_client_session.send_data(stype,Cmd.Request.Auth.RELOGIN,0,proto_type,null);

					netbus.remove_client_session(obj.id);
					netbus.session_close(prev_client_session);
				}

				client_session.session_id=obj.id;
				//client_session并不会删除
				netbus.remove_client_session(utag);
				//关联到新的session通道上
				netbus.set_client_session(obj.id,client_session);
			}
		}

		
		//清空用户标识,client的socket id
		body.writeUInt32BE(0,4);
		//直接发送到client
		client_session.send_cmd(body);

	},

	//被动接收到客户端的断开连接
	on_disconnect:function(session,stype){
		//将client的断开消息发给server_app
		var app_server_session=netbus.get_app_server_session(stype);
		if (!app_server_session){
			return;
		}

		//client的socket id
		var utag=session.session_id;
		app_server_session.send_data(stype,Cmd.Request.USER_DISCONNECT,utag,protocol.PROTO_JSON,null);
	}

}

module.exports = server;